package com.coupon.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

/**
 * @author 王哲
 * @Contact 1121586359@qq.com
 * @ClassName AbstractZuulFilter.java
 * @create 2023年06月23日 下午8:53
 * @Description 自定义抽象网关过滤器
 * @Version V1.0
 */

public abstract class AbstractZuulFilter extends ZuulFilter {

    // 用于在过滤器间传递消息 数据保存在每个请求的 ThreadLocal 中
    RequestContext requestContext;

    private final static String NEXT = "next";


    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        return (boolean) currentContext.getOrDefault(NEXT,true);
    }

    @Override
    public Object run() throws ZuulException {

        requestContext = RequestContext.getCurrentContext();

        return cRun();
    }

    protected abstract Object cRun();

    Object fail(int code,String msg){
        requestContext.set(NEXT,false);
        requestContext.setSendZuulResponse(false);
        requestContext.getResponse().setContentType("text/html;charset=UTF-8");
        requestContext.setResponseStatusCode(code);
        requestContext.setResponseBody(String.format(
                "{\"result\":\"%s!\"}",msg
        ));
        return null;
    }

    Object success(){

        requestContext.set(NEXT,true);
        return null;
    }

}
